<template>
  <Drawer title="收藏为模板"
          placement="left"
          v-model="visible"
          width="450"
          :mask-closable="false"
          :styles="$PnUtil.buildDrawerStyleByHasFooter()">
    <Alert show-icon style="text-align: justify; padding-right: 8px;">
      您可以将当前页面布局收藏，供您下次创建新页面时作为模板使用。
    </Alert>
    <Form ref="pageTemplateForm" :label-width="120" :model="formData" :rules="ruleValidate">
      <FormItem label="id" prop="id" hidden>
        <Input v-model="formData.id"/>
      </FormItem>
      <FormItem label="覆盖已有模板">
        <Select ref="pageTemplateSelect" :transfer="true" clearable @on-change="changeHandler">
          <Option v-for="item in allPageTemplate" :value="item.id" :key="item.id">{{ item.name }}</Option>
        </Select>
      </FormItem>
      <FormItem label="模板名称" prop="name">
        <Input v-model="formData.name" placeholder="请输入模板名称"/>
      </FormItem>
      <FormItem label="缩略图" prop="thumbnail">
        <Button type="default" size="small" @click="useCustomPageThumbnail">引用当前编辑页面的缩略图</Button>
        <div class="thumbnail-card">
          <Icon type="ios-image" v-if="!formData.thumbnail"/>
          <img v-if="formData.thumbnail" :src="$PnUtil.buildImageSrc(formData.thumbnail)" />
        </div>
        <UploadImageButton v-model="formData.thumbnail" :page-id="$PnUtil.getUrlParam('page_id')" :cacheSelectBtnVisible="false"></UploadImageButton>
      </FormItem>
      <FormItem v-permission label="系统模板" prop="is_sys">
        <Tooltip content="如果作为系统模板，建议页面中不要存在关联有动态数据源的组件" placement="top" :max-width="200">
          <i-switch v-model="formData.is_sys" :true-value="'1'" :false-value="'0'">
            <span slot="open"></span>
            <span slot="close"></span>
          </i-switch>
        </Tooltip>
      </FormItem>
      <FormItem label="激活使用" prop="enabled">
        <i-switch v-model="formData.enabled" :true-value="'1'" :false-value="'0'">
          <span slot="open"></span>
          <span slot="close"></span>
        </i-switch>
      </FormItem>
    </Form>
    <DrawerFooter>
      <Button class="m-r-5px" @click="visible = false">关闭</Button>
      <Button class="m-r-5px" type="default" @click="clearForm">清空表单</Button>
      <Button type="primary" @click="submitForm" :loading="loading">保存</Button>
    </DrawerFooter>
  </Drawer>
</template>

<script>

  export default {
    name: 'PageTemplateForm',
    data() {
      return {
        visible: false,
        loading: false,
        pageMetadata: null,
        allPageTemplate: [],
        formData: {
          id: '',
          name: '',
          thumbnail: '',
          develop_canvas: '',
          layout: '',
          theme_json: '',
          is_sys: '0',
          user_id: '',
          enabled: '0'
        },
        ruleValidate: {
          name: [
            { required: true, message: '模板名称不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    mounted() {
      this.loadAllPageTemplate();
    },
    methods: {

      initPageMetadata (pageMetadata) {
        this.visible = true
        this.pageMetadata = pageMetadata;
        this.formData.thumbnail = this.pageMetadata.thumbnail
      },

      loadAllPageTemplate () {
        this.$PnApi.PageTemplateApi.getAllPageTemplate().then(result => {
          this.allPageTemplate = result.data.payload
        })
      },

      useCustomPageThumbnail () {
        this.formData.thumbnail = this.pageMetadata.thumbnail
      },

      submitForm () {
        this.$refs.pageTemplateForm.validate((valid) => {
          if (valid) {
            this.loading = true
            let type = this.formData.id ? 'update': 'add';

            // 构建模板记录ID，同时此ID也作为模板附件文件夹的根目录文件名
            let newGuid = this.$PnUtil.uuid();
            if (type == 'add') {this.formData.id = newGuid}
            // 将当前编辑页面的布局信息中涉及到附件路径的，全部将原页面ID替换成模板记录ID
            this.formData.layout =
              JSON.stringify(this.pageMetadata.layout)
                .replaceAll(this.pageMetadata.id, type == 'add' ? newGuid : this.formData.id);

            this.formData.theme_json = JSON.stringify(this.pageMetadata.theme_json);
            // 更新模板缩略图的路径地址
            this.formData.thumbnail =
              this.formData.thumbnail.replaceAll(this.pageMetadata.id, type == 'add' ? newGuid : this.formData.id);

            this.formData.develop_canvas = this.pageMetadata.develop_canvas;

            this.$PnApi.PageTemplateApi.savePageTemplate(this.formData, type, newGuid).then(result => {
              if (result.data.success) {
                this.$refs.pageTemplateForm.resetFields();
                this.$Message.success('保存成功');
                this.loadAllPageTemplate();
                this.$refs.pageTemplateSelect.clearSingleSelect();

                // 进行附件资源转移，调用savePageTemplate会返回保存的模板记录的ID
                this.$PnApi.PageTemplateApi.attachmentResourceTransfer(this.pageMetadata.id, result.data.payload).then(result => {
                  if(!result.data.success) {
                    this.$Message.error(result.data.message)
                  }
                  this.loading = false
                })
              }else {
                this.$Message.error(result.data.message);
              }
            })
          }
        });
      },

      clearForm () {
        this.$refs.pageTemplateForm.resetFields();
        this.$refs.pageTemplateSelect.clearSingleSelect();
      },

      changeHandler (val) {
        if (val) {
          this.$PnApi.PageTemplateApi.getPageTemplateById(val).then(result => {
            this.formData = result.data.payload
          })
        }else {
          this.$refs.pageTemplateForm.resetFields();
        }
      },

    },
    computed: {},
    watch: {

    }
  }
</script>

<style lang="less" scoped>

  .thumbnail-card {
    width: 100%;
    height: 150px;
    background-color: #757575;
    padding: 5px;
    margin-bottom: 5px;
    position: relative;
    i {
      position: absolute;
      left: 50%;
      top: 50%;
      -webkit-transform: translate(-50%,-50%);
      -moz-transform: translate(-50%,-50%);
      transform:translate(-50%,-50%);
      font-size: 70px;
      color: #fff;
    }
    img {
      width: 100%;
      height: 100%;
    }
  }
</style>
